# CGCurrency v2.0

import urllib2
from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext import db
from xml.dom import minidom
from datetime import datetime

# Rates in following order: USD>EUR USD>GBP EUR>USD EUR>GBP GBP>USD GBP>EUR
rates = [0.70420, 0.62250, 1.42005, 0.88398, 1.60643, 1.13125]

class Rate(db.Model):
    currency = db.StringProperty(multiline=False)
    rate = db.FloatProperty()
    date = db.DateProperty(auto_now_add=True)

def currency_key(currency_table=None):
    return db.Key.from_path('Rate', currency_table or 'cgc_table')

# Main class, outputs the form
class MainPage(webapp.RequestHandler):
    def get(self):
        self.response.out.write("""
          <html>
            <head>
              <script type="text/javascript" src="jquery.min.js"></script>
              <script type="text/javascript" src="highcharts.min.js"></script>
            </head>
            <body>
              <h1>CGCurrency</h1>
              <form action="/convert" method="post">
                <div><input type="text" name="value" size="8" /></div>
                <div>
                  <select name="currencies">
                    <option value="0">USD &raquo; EUR</option>
                    <option value="1">USD &raquo; GBP</option>
                    <option value="2">EUR &raquo; USD</option>
                    <option value="3">EUR &raquo; GBP</option>
                    <option value="4">GBP &raquo; USD</option>
                    <option value="5">GBP &raquo; EUR</option>
                  </select>
                </div>
                <div><input type="submit" value="Convert" /></div>
              </form>
            </body>
          </html>""")
        rates = db.GqlQuery("SELECT * FROM Rate ORDER BY date DESC")
        for rate in rates:
            self.response.out.write('<pre>[%s] %s : %s</pre>' % (rate.date, rate.currency, rate.rate))

# Handle the form
class Converter(webapp.RequestHandler):
    def post(self):
        self.response.out.write('<html><h1>CGCurrency</h1><body>Result:<pre>')
        # Convert the currency
        result = float(self.request.get('value')) * rates[int(self.request.get('currencies'))]
        self.response.out.write(result)
        self.response.out.write('</pre></body></html>')


# Install the currencies from the past 90 days
class Installer(webapp.RequestHandler):
    def get(self):
        #TODO: datastore reset!
        url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml'
        dom = minidom.parse(urllib2.urlopen(url))
        for node in dom.getElementsByTagName('Cube'):
            cgc = Rate(parent=currency_key('cgc_table'))
            if node.getAttribute('time'):
                date = datetime.strptime(node.getAttribute('time'), '%Y-%m-%d').date()
            if node.getAttribute('currency'):
                cgc.date = date
                cgc.currency = node.getAttribute('currency')
                cgc.rate = float(node.getAttribute('rate'))
                cgc.put()
        print 'DONE'
        
# Update the currencies
class Updater(webapp.RequestHandler):
    def get(self):
        url = 'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml'
        dom = minidom.parse(urllib2.urlopen(url))
        for node in dom.getElementsByTagName('Cube'):
            cgc = Rate(parent=currency_key('cgc_table'))
            if node.getAttribute('currency'):
                cgc.currency = node.getAttribute('currency')
                cgc.rate = float(node.getAttribute('rate'))
                cgc.put()
                if cgc.currency=='USD':
                    rates[2]=cgc.rate
                    rates[0]=(1/cgc.rate)
                if cgc.currency=='GBP':
                    rates[3]=cgc.rate
                    rates[5]=(1/cgc.rate)
            rates[1]=rates[3]/rates[2]
            rates[4]=(1/rates[1])
        print 'DONE'
        print rates
# Register Converter class
application = webapp.WSGIApplication(
                                     [('/', MainPage),
                                      ('/convert', Converter),
                                      ('/update', Updater),
                                      ('/install', Installer)],
                                     debug=True)

def main():
    run_wsgi_app(application)

if __name__ == "__main__":
    main()

